/**
 * 下拉列表字典数据仓库
 */
import { dropDownBox, dropDownBoxByParentId, selectDistrict, getAllListOfSysOrg } from '../../apis/dictionary';

export const state = {};
export const mutations = {
  GET_DROPDOWN_DICTIONARY(state, payload) {
    state[payload.type] = payload.list;
  },
};

export const getters = {};
export const actions = {
  /**
   * 公共下拉字典
   * @param commit
   * @param state
   * @param code 字典code
   *        - status 审批状态
   * @returns {Promise<unknown>}
   */
  getDropdownBox({ commit, state }, code) {
    return new Promise((resolve, reject) => {
      if (!code) {
        resolve([]);
        return;
      }
      if (state[code] && state[code].length > 0) {
        resolve(state[code]);
        return;
      }
      dropDownBox(code).then(list => {
        commit('GET_DROPDOWN_DICTIONARY', { type: code, list });
        resolve(list);
      }).catch(() => reject());
    });
  },

  /**
   * 通过父级id获取下拉框子级数据
   * @param commit
   * @param state
   * @param pid
   */
  getDropDownBoxByParentId({ commit, state }, pid) {
    return new Promise((resolve, reject) => {
      if (!pid) {
        resolve([]);
        return;
      }
      if (state[pid] && state[pid].length > 0) {
        resolve(state[pid]);
        return;
      }

      dropDownBoxByParentId(pid).then(list => {
        commit('GET_DROPDOWN_DICTIONARY', { type: pid, list });
        resolve(list);
      }).catch(() => reject());
    });
  },

  /**
   * 行业主管单位下拉
   * @param commit
   * @param state
   * @param unit
   * @returns {Promise<unknown>}
   */
  getAllList({ commit, state }, payload) {
    return new Promise((resolve, reject) => {
      if (!payload) {
        resolve([]);
        return;
      }

      if (state[payload] && state[payload].length > 0) {
        resolve(state[payload]);
        return;
      }

      if (payload === 'jdlx') {
        const list = [
          { value: '人文历史', code: '1' },
          { value: '自然风光', code: '2' },
        ];
        commit('GET_DROPDOWN_DICTIONARY', { type: payload, list });
        resolve(list);
      } else if (payload === 'unit') {
        // 行业主管单位下拉
        getAllListOfSysOrg().then(list => {
          list.forEach(item => {
            item.dictCode = item.orgCode;
            item.dictName = item.orgName;
          });
          commit('GET_DROPDOWN_DICTIONARY', { type: payload, list });
          resolve(list);
        }).catch(() => reject());
      } else if (payload === 'area') {
        // 行政区域
        selectDistrict().then(list => {
          list.forEach(item => {
            item.dictCode = item.distCode;
            item.dictName = item.distName;
          });
          commit('GET_DROPDOWN_DICTIONARY', { type: payload, list });
          resolve(list);
        }).catch(() => reject());
      } else {
        resolve();
      }
    });
  },
};
